<template>
  <div class="plan-edit">
    <a-form :form="form" :label-col="{ span: 6, sm: 8, lg: 6 }" :wrapper-col="{ span: 7, sm: 12, lg: 7 }" @submit="handleSubmit">
      <div class="box">
        <span style="font-size:20px;">基本信息</span>
      </div>
      <a-form-item label="计划名称">
        <a-input
          placeholder="请给计划取个名字，32字以内"
          v-decorator="['planName', { rules: [{ required: true, message: '必须填写素材名称' }] }]"
        />
      </a-form-item>
      <a-form-item label="计划类型">
        <a-radio-group :disabled="true" @change="radioChange" v-decorator="['planType']">
          <a-radio :value="0">
            互动广告
          </a-radio>
          <a-radio :value="1">
            直投广告
          </a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item label="落地页链接">
        <a-textarea
          placeholder="请填写广告落地页链接,多连接请使用回车换行分隔"
          v-decorator="['planLandUrl', { rules: [{ required: true, message: '广告落地页不能为空' }] }]"
        />
      </a-form-item>
      <div v-if="planType">
        <a-form-item label="广告素材">
          <a-select
            placeholder="请输入素材名称"
            mode="tags"
            v-decorator="['materialIds', { rules: planType ? [{ required: true, message: '广告素材不能为空' }] : '' }]"
            style="width: 100%"
            :token-separators="[',']"
          >
            <a-select-option v-for="items in materialChildType" :value="items.id.toString()" :key="items.id.toString()">
              {{ `[${items.id}] ${items.materialName}` }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <div class="links">
          <a @click="toMaterialCreate">新建素材</a>
        </div>
      </div>
      <a-form-item label="计费">
        <a-radio-group v-decorator="['planSortType']">
          <a-radio :value="0">
            CPM
          </a-radio>
          <a-radio :value="1">
            CPC
          </a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item label=" " :colon="false"> <a-input-number placeholder="0~100" :min="0" v-decorator="['planCpm']" /> 元 </a-form-item>
      <a-form-item label="广告主">
        <a-select placeholder="请选择广告主" v-decorator="['subUserId']" style="width: 100%" :token-separators="[',']">
          <a-select-option v-for="items in adverType" :value="items.id" :key="items.id">
            {{ items.username }}{{ items.userDesc ? `-${items.userDesc}` : '' }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <div v-show="planType">
        <div class="box">
          <span style="font-size:20px;">投放限额</span>
        </div>
        <a-form-item label="日限额方式">
          <a-radio-group @change="handleLimitRadio" v-decorator="['dailyLimitType']">
            <a-radio :value="0">
              不限制
            </a-radio>
            <a-radio :value="4">
              预算
            </a-radio>
            <a-radio :value="1">
              曝光
            </a-radio>
            <a-radio :value="2">
              点击
            </a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="日限额">
          <a-input :disabled="limitChecked == 0" v-decorator="['dailyLimitCount']" />
        </a-form-item>
        <div class="box">
          <span style="font-size: 20px">投放时间</span>
        </div>
        <a-form-item label="投放时间段">
          <a-radio-group @change="dailyLimitTimeChange" v-decorator="['dailyLimitTime']">
            <a-radio :value="1">全天</a-radio>
            <a-radio :value="2">自定义时间段</a-radio>
          </a-radio-group>
        </a-form-item>
        <div v-if="isDailyLimitTime">
          <a-form-item label="每日开投时间">
            <a-time-picker
              :defaultValue="moment(startTime, 'HH:mm:ss')"
              :default-open-value="moment('00:00:00', 'HH:mm:ss')"
              @change="startTimeValue"
            />
          </a-form-item>
          <a-form-item label="每日关闭时间">
            <a-time-picker
              :defaultValue="moment(endTime, 'HH:mm:ss')"
              :default-open-value="moment('00:00:00', 'HH:mm:ss')"
              @change="endTimeValue"
            />
          </a-form-item>
        </div>
        <div class="box">
          <span style="font-size:20px;">定向投放</span>
        </div>
        <a-form-item label="投放广告位">
          <a-radio-group @change="regionSlotChange" v-decorator="['filterType']">
            <a-radio :value="0">
              通投
            </a-radio>
            <a-radio @click="showSlotModal" :value="1">
              {{ slotRadioCurrent == 1 ? `白名单(${slotValue.length})` : `白名单(0)` }}
            </a-radio>
            <a-radio @click="showSlotModal" :value="2">
              {{ slotRadioCurrent == 2 ? `黑名单(${slotValue.length})` : `黑名单(0)` }}
            </a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="投放区域">
          <a-radio-group @change="regionChange" v-decorator="['regionFilterType']">
            <a-radio :value="0">
              通投
            </a-radio>
            <a-tooltip placement="top">
              <template slot="title">
                <span>{{ radioCurrent == 1 ? cityValue.toString() : '' }}</span>
              </template>
              <a-radio @click="showCityModal" :value="1">
                {{ radioCurrent == 1 ? `白名单(${cityValue.length})` : `白名单(0)` }}
              </a-radio>
            </a-tooltip>
            <a-tooltip placement="top">
              <template slot="title">
                <span>{{ radioCurrent == 2 ? cityValue.toString() : '' }}</span>
              </template>
              <a-radio @click="showCityModal" :value="2">
                {{ radioCurrent == 2 ? `黑名单(${cityValue.length})` : `黑名单(0)` }}
              </a-radio>
            </a-tooltip>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="媒体类型">
          <a-checkbox-group v-decorator="['filterEnv']">
            <a-checkbox value="1">
              微信
            </a-checkbox>
            <a-checkbox value="2">
              支付宝
            </a-checkbox>
            <a-checkbox value="3">
              百度
            </a-checkbox>
            <a-checkbox value="0">
              其他
            </a-checkbox>
          </a-checkbox-group>
        </a-form-item>
        <a-form-item label="操作系统">
          <a-checkbox-group v-decorator="['filterOS']">
            <a-checkbox value="1">
              Android
            </a-checkbox>
            <a-checkbox value="2">
              iOS
            </a-checkbox>
            <a-checkbox value="0">
              其他
            </a-checkbox>
          </a-checkbox-group>
        </a-form-item>
        <a-form-item label="运营商">
          <a-checkbox-group v-decorator="['filterIsp']">
            <a-checkbox value="中国移动">
              中国移动
            </a-checkbox>
            <a-checkbox value="中国联通">
              中国联通
            </a-checkbox>
            <a-checkbox value="中国电信">
              中国电信
            </a-checkbox>
            <a-checkbox value="其他">
              其他
            </a-checkbox>
          </a-checkbox-group>
        </a-form-item>
      </div>
      <a-form-item :wrapper-col="{ span: 12, offset: 6 }">
        <a-space>
          <a-button type="primary" html-type="submit">
            保存
          </a-button>
          <a-popconfirm placement="top" ok-text="确定" cancel-text="取消" @confirm="confirmUnShow">
            <template slot="title">
              <p>下架后不可恢复，请谨慎操作。是否确认下架？</p>
            </template>
            <a-button type="danger">
              下架
            </a-button>
          </a-popconfirm>
        </a-space>
      </a-form-item>
    </a-form>
    <a-modal width="70%" v-model="cityModalVisible" title="选择城市" @ok="handleOk">
      <a-tree-select
        v-model="cityValue"
        style="width: 100%;"
        :tree-data="cityData"
        :dropdownStyle="{
          height: '350px',
        }"
        tree-checkable
        :show-checked-strategy="SHOW_PARENT"
        search-placeholder="Please select"
      />
    </a-modal>
    <a-modal width="70%" v-model="slotModalVisible" title="选择广告位" @ok="handleSlotOk">
      <a-select :default-value="slotValue" mode="tags" @change="handleChange" placeholder="请选择广告位" style="width: 100%">
        <a-select-option v-for="items in slotsList" :value="items.slotKey" :key="items.id.toString()">
          {{ items.slotName }}
        </a-select-option>
      </a-select>
    </a-modal>
  </div>
</template>

<script>
import moment from 'moment'
import { TreeSelect } from 'ant-design-vue'
import { postAdvertPlanUpdate, getAdvertPlanGet, postAdvertPlanUnShow } from '@/api/Advertising/api'
import { getSubUserListAdvert } from '@/api/accountMan/api'
import { getMaterialList } from '@/api/Advertising/api'
import { getSlotList } from '@/api/MeidaMan/api'
import { toRoute } from '@/lib/utils'
import cityData from '@/mock/city/city'
const SHOW_PARENT = TreeSelect.SHOW_PARENT
export default {
  name: 'PlanEdit',
  data() {
    return {
      moment,
      SHOW_PARENT,
      cityData: cityData[0]?.children ?? [],
      slotData: cityData[0]?.children ?? [],
      limitChecked: 0,
      formLayout: 'horizontal',
      planType: true,
      form: this.$form.createForm(this, { name: 'myForm' }),
      radioCurrent: 0,
      slotRadioCurrent: 0,
      materialChildType: [],
      adverType: [],
      cityModalVisible: false,
      slotModalVisible: false,
      cityValue: [],
      slotValue: [],
      slotsList: [],
      filterSlot: [],
      id: '',
      isDailyLimitTime: false,
      startTime: '00:00:00',
      endTime: '00:00:00',
    }
  },
  mounted() {
    this.$nextTick(() => {
      const { id } = this.$route.query
      this.id = id
      this.advertPlanGet(id)
      this.subUserListAdvert()
      this.slotList()
      this.materialList({
        name: '',
        advertType: 0,
        pageSize: 200,
      })
    })
  },
  methods: {
    /**
     * @func 开始时间
     */
    startTimeValue(v) {
      this.startTime = moment(v).format('HH:mm:ss')
    },
    /**
     * @func 结束时间
     */
    endTimeValue(v) {
      this.endTime = moment(v).format('HH:mm:ss')
    },
    /**
     * @func 投放时间段
     */
    dailyLimitTimeChange({ target: { value } }) {
      value == 2 ? (this.isDailyLimitTime = true) : (this.isDailyLimitTime = false)
    },
    handleChange(value) {
      this.filterSlot = value
      this.slotValue = value
    },
    /**
     * @func 列表数据
     */
    async slotList(param) {
      try {
        const data = await getSlotList({ ...param })
        if (data) {
          const list = data?.list ?? []
          // const newArr = list.filter((item) => {
          //   return this.slotValue.includes(item.slotKey)
          // })
          this.slotsList = list
        }
      } catch (err) {
        this.$msgErr(err.message)
      }
    },
    /**
     * @func 跳转新建素材
     */
    toMaterialCreate() {
      toRoute(this, 'material-create')
    },
    /**
     * @func 下架确认框
     */
    confirmUnShow() {
      const id = this.id
      this.advertPlanUnShow(id)
    },
    /**
     * @func 计划编辑下架
     */
    async advertPlanUnShow(id) {
      const [err, data] = await postAdvertPlanUnShow({ id })
      if (!err) {
        this.$msgSuc('提交成功!')
        toRoute(this, '/plan')
      } else {
        this.$msgErr(err)
      }
    },
    /**
     * @func 表单回显数据
     */
    async advertPlanGet(id) {
      const [err, data] = await getAdvertPlanGet({ id })
      if (!err) {
        data?.planType == 1 ? (this.planType = false) : (this.planType = true)
        data?.dailyLimitTime == 1 ? (this.isDailyLimitTime = false) : (this.isDailyLimitTime = true)
        const filterRegion = data?.['filterRegion']?.split(',') ?? []
        const filterSlot = data?.['filterSlot']?.split(',') ?? []
        const dailyLimitType = data?.['dailyLimitType']
        this.limitChecked = dailyLimitType
        const regionFilterType = data?.['regionFilterType']
        const filterType = data?.['filterType']
        this.cityValue = filterRegion.filter(Boolean)
        this.slotValue = filterSlot.filter(Boolean)
        this.radioCurrent = regionFilterType
        this.slotRadioCurrent = filterType
        this.startTime = data?.['startTime'] ?? '00:00:00'
        this.endTime = data?.['endTime'] ?? '00:00:00'
        const access = {
          planCpm: data?.['planCpm'] / 100 ?? 0,
          filterEnv: data?.['filterEnv'].split(',') ?? [],
          filterIsp: data?.['filterIsp'].split(',') ?? [],
          filterOS: data?.['filterOS'].split(',') ?? [],
          materialIds: data?.['materialIds'].map((item) => String(item)) ?? [],
        }
        const values = {
          ...data,
          ...access,
        }
        this.form.setFieldsInitialValue(values)
      }
    },
    /**
     * @func 编辑保存计划
     */
    async advertPlanUpdate(param) {
      const [err, data] = await postAdvertPlanUpdate(param)
      if (!err) {
        this.$msgSuc('提交成功!')
        toRoute(this, '/plan')
      } else {
        this.$msgErr(err)
      }
    },
    /**
     * @func 点击确认模态框
     */
    handleOk() {
      this.cityModalVisible = false
    },
    handleSlotOk() {
      this.slotModalVisible = false
    },
    /**
     * @func 显示城市选择
     */
    showCityModal() {
      this.cityModalVisible = true
    },
    showSlotModal() {
      this.slotModalVisible = true
    },
    /**
     * @func 投放区域切换
     */
    regionChange(e) {
      const value = e.target.value
      this.radioCurrent = value
    },
    regionSlotChange(e) {
      const value = e.target.value
      this.slotRadioCurrent = value
    },
    /**
     * @func 广告子账号列表
     */
    async subUserListAdvert() {
      const data = await getSubUserListAdvert()
      data.unshift({
        username: '请选择',
        id: 0,
      })
      this.adverType = data
    },
    /**
     * @func 广告素材列表
     */
    async materialList(param) {
      const data = await getMaterialList({ param })
      this.materialChildType = data?.list ?? []
    },
    /**
     * @func 单选框切换
     */
    radioChange(e) {
      if (e.target.value == 1) {
        this.planType = false
      } else {
        this.planType = true
      }
    },
    handleSubmit(e) {
      e.preventDefault()
      const id = this.id || ''
      const startTime = this.startTime
      const endTime = this.endTime
      this.form.validateFields((err, fieldsValue) => {
        if (!err) {
          /**
           * @dec planType为互动广告类型
           */
          if (this.planType) {
            const access = {
              planCpm: fieldsValue['planCpm'] * 100,
              filterEnv: fieldsValue['filterEnv'].toString(),
              filterOS: fieldsValue['filterOS'].toString(),
              filterIsp: fieldsValue['filterIsp'].toString(),
              materialIds: fieldsValue['materialIds'].map((item) => Number(item)),
              filterRegion: this.cityValue.toString(),
              filterSlot: this.slotValue.toString(),
              planLandFormContentConfig: undefined,
              landPageLog: 0,
              id,
              startTime,
              endTime,
            }
            const values = {
              ...fieldsValue,
              ...access,
            }
            this.advertPlanUpdate(values)
          } else {
            const accsee = {
              planCpm: fieldsValue['planCpm'] * 100,
              filterEnv: fieldsValue['filterEnv'].toString(),
              filterOS: fieldsValue['filterOS'].toString(),
              filterIsp: fieldsValue['filterIsp'].toString(),
              materialIds: null,
              filterRegion: '',
              filterSlot: '',
              planLandFormContentConfig: undefined,
              landPageLog: 0,
              id,
            }
            const values = {
              ...fieldsValue,
              ...accsee,
            }
            this.advertPlanUpdate(values)
          }
        }
      })
    },
    /**
     * 日限额radio切换
     */
    handleLimitRadio(e) {
      this.limitChecked = e.target.value
    },
  },
}
</script>
<style lang="scss" scoped>
.box {
  margin-left: 13%;
  margin-bottom: 15px;
}
.links {
  margin-left: 25%;
}
</style>
